package com.songdehuai.supermarket;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.songdehuai.supermarket.base.BaseAcitivity;
import com.songdehuai.supermarket.presenter.MainPresenter;
import com.songdehuai.supermarket.presenter.imp.MainPresenterImp;
import com.songdehuai.supermarket.supermarket.adapter.ShopNameListAdapter;
import com.songdehuai.supermarket.supermarket.entity.Shop;
import com.songdehuai.supermarket.sync.MainSync;
import com.songdehuai.widget.myrefreshlayout.MyRefreshLayout;
import com.songdehuai.widget.myrefreshlayout.RefreshListenerAdapter;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseAcitivity implements MainSync {

    @ViewInject(R.id.main_lv)
    ListView mainLv;
    @ViewInject(R.id.reshLayout)
    MyRefreshLayout refreshLayout;

    MainPresenter presenter;

    ShopNameListAdapter shopListAdapter;

    List<Shop> shopList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        x.view().inject(this);
        init();
    }

    private void init() {
        presenter = new MainPresenterImp(MainActivity.this, this);
        shopList = new ArrayList<>();
        shopListAdapter = new ShopNameListAdapter(MainActivity.this, shopList);
        mainLv.setAdapter(shopListAdapter);
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(MyRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                presenter.getShopList(false);
            }

            @Override
            public void onLoadMore(MyRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
            }
        });
        refreshLayout.startRefresh();
        mainLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getApplicationContext(), SuperMarketActivity.class);
                intent.putExtra("ID", shopList.get(i).getId() + "");
                startActivity(intent);
            }
        });
    }

    @Override
    public void showShopList(boolean isLoadMore, List<Shop> listShop) {
        if (!isLoadMore) {
            this.shopList.clear();
        }
        this.shopList.addAll(listShop);
        shopListAdapter.notifyDataSetChanged();
        refreshLayout.finish();
    }
}
